/*
 * Copyright (c) 2008, intarsys consulting GmbH
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Public License as published by the 
 * Free Software Foundation; either version 3 of the License, 
 * or (at your option) any later version.
 * <p/>
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * 
 */
package de.intarsys.pdf.example.extract.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import de.intarsys.pdf.cos.COSObjectWalkerDeep;
import de.intarsys.pdf.cos.COSStream;
import de.intarsys.pdf.cos.COSVisitorException;
import de.intarsys.pdf.example.common.CommonJPodRendererExample;
import de.intarsys.pdf.pd.PDImage;
import de.intarsys.pdf.pd.PDObject;
import de.intarsys.pdf.platform.cwt.image.awt.ImageConverterPdf2Awt;

/**
 * Extract all images in the document.
 * 
 */
public class ExtractImages extends CommonJPodRendererExample {

	public static int SCALE = 2;

	public static void main(String[] args) {
		ExtractImages client = new ExtractImages();
		try {
			client.run(args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void extractImage(ImageWriter writer, PDImage pdImage,
			String filename, int i) throws IOException {
		ImageConverterPdf2Awt converter = new ImageConverterPdf2Awt(pdImage);
		final BufferedImage image = converter.getBufferedImage();
		//
		File outputFile = new File(filename + "." + i + ".png");
		ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
		try {
			writer.setOutput(ios);
			writer.write(new IIOImage(image, null, null));
		} finally {
			writer.reset();
			ios.flush();
			ios.close();
		}
	}

	@SuppressWarnings("rawtypes")
	protected void extractImages(final String filename)
			throws COSVisitorException {
		Iterator iter = ImageIO.getImageWritersByFormatName("png");
		if (!iter.hasNext()) {
			return;
		}
		final ImageWriter writer = (ImageWriter) iter.next();
		try {
			COSObjectWalkerDeep walker = new COSObjectWalkerDeep() {
				private int i = 0;

				@Override
				public Object visitFromStream(COSStream stream)
						throws COSVisitorException {
					if (!PDImage.CN_Subtype_Image.equals(stream.getDict().get(
							PDObject.DK_Subtype))) {
						return null;
					}
					PDImage image = (PDImage) PDImage.META
							.createFromCos(stream);
					if (image == null) {
						return null;
					}
					try {
						extractImage(writer, image, filename, i++);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
			};
			getDoc().cosGetDoc().getCatalog().cosGetObject().accept(walker);
		} finally {
			writer.dispose();
		}
	}

	public void run(String[] args) throws Exception {
		if (args.length < 1) {
			usage();
			return;
		}
		try {
			String inputFileName = args[0];
			open(inputFileName);
			extractImages(inputFileName);
		} finally {
			close();
		}
	}

	/**
	 * Help the user.
	 */
	public void usage() {
		System.out.println("usage: java.exe " + getClass().getName() //$NON-NLS-1$
				+ " <input-pdf>"); //$NON-NLS-1$
	}
}
